package ctu.kfad.run;

import ctu.kfad.run.memory.ArraySizeDescriptor;

public class ObjectTable {

    private InstanceDescriptor[] descriptors = new InstanceDescriptor[1000];

    public int saveNewObject(String className, int referenceInMemory) {
        int index = findFreeAddress();
        descriptors[index] = InstanceDescriptor.create(className, referenceInMemory);
        return index;
    }

    public int saveNewArray(ArraySizeDescriptor descriptor, int referenceInMemory) {
        int index = findFreeAddress();
        descriptors[index] = InstanceDescriptor.create(descriptor, referenceInMemory);
        return index;
    }


    private int findFreeAddress() {
        for (int i = 1; i < descriptors.length; i++) {
            if (descriptors[i] == null || !descriptors[i].isLive()) {
                return i;
            }
        }
        throw new RuntimeException("NOt enough space in object table");
    }

    public int findReferenceInMemory(int index) {
        return descriptors[index].getReferenceToMemory();
    }

    public InstanceDescriptor getDescriptorForAddress(int index) {
        return descriptors[index];
    }

    public String findClassName(int index) {
        return descriptors[index].getClassName();
    }

    public InstanceDescriptor[] getDescriptors() {
        return descriptors;
    }

}
